package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/star-find-cloud/star-safe/conf"
	"github.com/star-find-cloud/star-safe/pkg/database"
	"github.com/star-find-cloud/star-safe/pkg/logger"
	"github.com/star-find-cloud/star-safe/user"
)

func main() {
	// 初始化配置
	config := conf.GetConfig()
	
	// 初始化数据库连接
	_ = database.GetDB() // 触发数据库连接初始化
	
	// 设置Gin模式
	if config.App.Debug {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	
	// 创建Gin路由
	router := gin.Default()
	
	// 设置中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())
	
	// 设置用户模块
	user.SetupUserModule(router)
	
	// 健康检查接口
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ok",
			"timestamp": time.Now().Unix(),
			"service":   config.App.Name,
			"version":   config.App.Version,
		})
	})
	
	// 启动HTTP服务器
	server := &http.Server{
		Addr:           fmt.Sprintf(":%d", config.App.Port),
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	
	logger.MySQLLogger.Infof("服务器启动成功，监听端口: %d", config.App.Port)
	logger.MySQLLogger.Infof("服务名称: %s", config.App.Name)
	logger.MySQLLogger.Infof("服务版本: %s", config.App.Version)

	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		logger.MySQLLogger.Fatalf("服务器启动失败: %v", err)
	}
}
